package com.github_dididipapa.mallsearch.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @description: ElasticSearchConfiguration
 * @author: dididi_papa
 * @email: mitis1624087624@gmail.com
 * @date: 2025/07/01  17:07
 */
@RefreshScope
@Configuration
public class ElasticSearchConfig {
    /**
     * @description: nacos 维护真实ip
     **/
    @Value("${elasticsearch.ip}")
    private String ip;
    @Value("${elasticsearch.port}")
    private int port;
    @Value("${elasticsearch.scheme}")
    private String scheme;
    @Value("${elasticsearch.username}")
    private String username;
    @Value("${elasticsearch.password}")
    private String password;

    /**
     * @description: 创建ES Client实例
     * @author: dididi_papa
     * @date: 2025/7/2 下午12:52
     * @param: []
     * @return: org.elasticsearch.client.RestHighLevelClient
     **/
    @Primary
    @Bean
    public RestHighLevelClient client() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(ip, port, scheme));
        // 配置认证信息
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));

        builder.setHttpClientConfigCallback(httpClientBuilder ->
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));

        return new RestHighLevelClient(builder);
    }

    @Bean
    public UsernamePasswordToken token() {
        return new UsernamePasswordToken(username, password);
    }
}
